//
//  AppDelegate+Func.swift
//  Auscultation
//
//  Created by 来 on 2020/11/28.
//

import Foundation

extension AppDelegate {
    
    // 自动登录
    func autoLogin() {
        // 版本更新检测
        if !EWEUrl.isZJ() {
//            checkVersion()
        }
        // 进入 app
        if EWEUser.lgf.accessToken.count > 0 {
            window!.rootViewController = MainNaviVC.init(rootViewController: MainVC())
        } else {
            window!.rootViewController = MainNaviVC.init(rootViewController: LoginVC())
        }
    }
    
    // 创建本地沙盒存放音频文件的文件夹
    func creatPcmFile() {
        let pcmPath = LGF_Documents_PCM;
        let wavPath = LGF_Documents_WAV;
        let fileManager = FileManager.default
        let pcmExisted = fileManager.fileExists(atPath: pcmPath)
        let wavExisted = fileManager.fileExists(atPath: wavPath)
        if !pcmExisted {
            do {
                try fileManager.createDirectory(atPath: pcmPath, withIntermediateDirectories: true, attributes: nil)
            } catch {
                debugPrint(error)
            }
        }
        if !wavExisted {
            do {
                try fileManager.createDirectory(atPath: wavPath, withIntermediateDirectories: true, attributes: nil)
            } catch {
                debugPrint(error)
            }
        }
    }

    // 版本更新
//    func checkVersion() {
//        let myVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
//        var paramet: [String: String] = [:]
//        paramet.updateValue("1", forKey: "scope")
//        paramet.updateValue(myVersion, forKey: "version")
//        EWERequest.lgf(LGF.hidoctor_version_get, paramet, { [weak self] (json) in
//            if let result = json as? [String: Any] {
//                let type = result[LGF.type] as! String
//                let url = result[LGF.url] as! String
//                let content = result[LGF.content] as! String
//                if type == "1" {// 普通更新
//                    self?.remindAppUpdate(url, type, content)
//                } else if type == "2" {// 强制更新
//                    self?.remindAppUpdate(url, type, content)
//                }
//            }
//        }) { (error) in }
//    }
//    func remindAppUpdate(_ url: String, _ type: String, _ content: String) {
//        let alter = UIAlertController(title: LGF.print32, message: content, preferredStyle: UIAlertController.Style.alert)
//        let cancelAction = UIAlertAction(title: "马上去更新", style: UIAlertAction.Style.cancel, handler: { (action) in
//            if #available(iOS 10.0, *) {
//                UIApplication.shared.open(URL.init(string: url)!, options: [:], completionHandler: nil)
//            } else {
//                // Fallback on earlier versions
//                UIApplication.shared.openURL(URL.init(string: url)!)
//            }
//            DispatchQueue.main.async {
//                UIApplication.shared.keyWindow?.rootViewController?.present(alter, animated: true, completion: nil)
//            }
//        })
//        alter.addAction(cancelAction)
//        if type == "1" {
//            let otherAction = UIAlertAction(title: "暂不更新", style: UIAlertAction.Style.default, handler: { (action) in
//                alter.dismiss(animated: true, completion: nil)
//            })
//            alter.addAction(otherAction)
//        }
//        UIApplication.shared.keyWindow?.rootViewController?.present(alter, animated: true, completion: nil)
//    }
}

extension UIResponder {
    
    func removePcm(_ path: String) {
        let fileManager = FileManager.default
        do {
            try fileManager.removeItem(atPath: path)
            debugPrint(path + "删除成功")
        } catch {
            debugPrint(path + "删除失败")
        }
    }
    
    func clearFile(_ path: String) {
        let fileManager = FileManager.default
        do {
            try fileManager.removeItem(atPath: path)
            let existed = fileManager.fileExists(atPath: path)
            if !existed {
                do {
                    try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
                } catch {
                    debugPrint(error)
                }
            }
        } catch {
            debugPrint(error)
        }
    }
    
    func stringToAscii(_ c: Character) ->Int {
        var numberFromC = 0
        //使用for-in循环遍历转化成String的“B”
        for scalar in String(c).unicodeScalars {
            //字符串只有一个字符，这个循环只会执行1次
            numberFromC = Int(scalar.value)
        }
        return numberFromC
    }
    
    // 十六进制转十进制
    func changeToInt(_ num: String) -> Int {
        let str = num.uppercased
        var sum = 0
        for i in str().utf8 {
            sum = sum * 16 + Int(i) - 48 // 0-9 从48开始
            if i >= 65 {                 // A-Z 从65开始，但有初始值10，所以应该是减去55
                sum -= 7
            }
        }
        return sum
    }
    
    func getStrCountArray(_ str: String, _ count: Int) -> [String] {
        var array: [String] = []
        var ffp = ""
        var ffi = 0
        str.forEach { (c) in
            ffp += String(c)
            ffi += 1
            if ffi % count == 0 {
                array.append(ffp)
                ffp = ""
                ffi = 0
            }
        }
        return array
    }
    
}

extension StringProtocol {
    var hexaData: Data { .init(hexa) }
    var hexaBytes: [UInt8] { .init(hexa) }
    private var hexa: UnfoldSequence<UInt8, Index> {
        sequence(state: startIndex) { start in
            guard start < self.endIndex else { return nil }
            let end = self.index(start, offsetBy: 2, limitedBy: self.endIndex) ?? self.endIndex
            defer { start = end }
            return UInt8(self[start..<end], radix: 16)
        }
    }
}
